/**
 * 
 */
package pt.inescid.components.messages;

import java.io.IOException;

import rice.p2p.commonapi.Endpoint;
import rice.p2p.commonapi.Message;
import rice.p2p.commonapi.rawserialization.InputBuffer;
import rice.p2p.commonapi.rawserialization.OutputBuffer;
import rice.p2p.commonapi.rawserialization.RawMessage;

/**
 * @author Sergio Esteves
 *
 */
public class TaskResult implements RawMessage {

	public static final short TYPE = 3;	
	
	private int jobHandler;
	
	private int taskNumber;
	
	private byte[] data;
	
	private double workDone = 0;
	
	private static final long serialVersionUID = 7526472295622776147L;
	
	public TaskResult(int jobHandler, int taskNumber, byte[] data) {
		this.jobHandler = jobHandler;
		this.taskNumber = taskNumber;
		this.data = data;
	}
	
	public TaskResult(int jobHandler, int taskNumber, byte[] data, double workDone) {
		this(jobHandler, taskNumber, data);
		this.workDone = workDone;
	}

	public int getJobHandler() {
		return jobHandler;
	}
	public int getTaskNumber() {
		return taskNumber;
	}
	public byte[] getData() {
		return data;
	}
	public double getWorkDone() {
		return workDone;
	}
	public int getPriority() {
		return Message.LOW_PRIORITY;
	}

	public short getType() {
		return TYPE;
	}

	public String toString() {
		return "TaskResult (jobHandler: " + jobHandler + ", taskNumber: " + taskNumber + ")"; 
	}
	
	/**
	 * Deserializing constructor.  This does the "real" deserialization.
	 * 
	 * @param buf
	 * @param endpoint
	 * @throws IOException
	 */
	public TaskResult(InputBuffer buf, Endpoint endpoint) throws IOException {
		jobHandler = buf.readInt();
		taskNumber = buf.readInt();
		data = new byte[buf.readInt()];
		buf.read(data);
		workDone = buf.readDouble();
	}

	public void serialize(OutputBuffer buf) throws IOException {
		buf.writeInt(jobHandler);
		buf.writeInt(taskNumber);
		buf.writeInt(data.length);
		buf.write(data, 0, data.length);
		buf.writeDouble(workDone);
	}
}
